# 21. 数字游戏

21

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

const lines = [];
rl.on('line', (line) => {
    const m = find(parseInt(line, 10));
    console.log(m);
});

function find(n) {
    let c0=0;
    let c1=0;
    let temp = n;
    // 统计0的个数
    while((temp & 1) === 0 && temp !== 0) {
        c0++;
        temp >>=1;
    }
    // 统计1的个数
    while((temp & 1) === 1) {
        c1++;
        temp >>=1;
    }
    if (c0 + c1 === 31 || c0 + c1 === 0) {
        return -1;
    }
    let p = c0+c1;
    n|=(1<<p);// 将p位置设为1
    n&=~((1<<p)-1); // 清除p位右边的所有位
    n|=(1<<(c1-1)) - 1;// p位右边插入(c1-1)个1
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34